package org.simple.service.impl;

import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.simple.service.ISmsService;
import org.simple.util.AjaxResult;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@Service
public class SmsServiceImpl implements ISmsService {
    @Override
    public AjaxResult sendSmsCode(Map<String, String> params) {
        PostMethod post=null;
        try {
        HttpClient client = new HttpClient();
         post = new PostMethod("http://utf8.api.smschinese.cn");
        post.addRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=utf-8");//在头文件中设置转码
        /*  map转为list，再转为array*/
        List<NameValuePair> dataAll =new ArrayList<>();
        for(String key:params.keySet()){
            dataAll.add(new NameValuePair(key,params.get(key)));
        }
        NameValuePair[] data=dataAll.toArray(new NameValuePair[]{});
        post.setRequestBody(data);
        client.executeMethod(post);

        Header[] headers = post.getResponseHeaders();
        int statusCode = post.getStatusCode();
        System.out.println("statusCode:"+statusCode);
        String result = new String(post.getResponseBodyAsString().getBytes("utf-8"));
        System.out.println(result); //打印返回消息状态
        if(statusCode==200){
            return AjaxResult.me().setMessage(result);
        }else{
            return AjaxResult.me().setSuccess(false).setMessage(result);
        }


        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(post!=null){
                post.releaseConnection();
            }
        }
        return  null;

    }
}
